<template>
	<view class="order-submission">
		<view class="allAddress" :style="systemStore ? '' : 'padding-top: 0.2*100rpx'">
			<!-- <view class="nav acea-row">
				<view class="item font-color-red" :class="shipping_type === 0 ? 'on' : 'on2'" @click="addressType(0)"
					v-if="systemStore"></view>
				<view class="item font-color-red" :class="shipping_type === 1 ? 'on' : 'on2'" @click="addressType(1)"
					v-if="systemStore"></view>
			</view> -->
			<!-- {{JSON.stringify(systemStore)}} -->
			<view class="nav acea-row">
				<view class="item" style="height: 88rpx; line-height: 88rpx; text-align: center;" :class="shipping_type === 0 ? 'active' : ''" @click="addressType(0)"
					v-if="systemStore && merId == '0'">快递配送</view>
				<view class="item" style="height: 88rpx; line-height: 88rpx; text-align: center;" :class="shipping_type === 1 ? 'active' : ''" @click="addressType(1)"
					v-if="systemStore">到店自提</view>
					<!-- && merId !='0'  直营商品没有本地配送 -->
				<view class="item" style="height: 88rpx; line-height: 88rpx; text-align: center;" :class="shipping_type === 2 ? 'active' : ''" @click="addressType(2)"
					v-if="systemStore && merId !='0'">本地配送</view>
			</view>
			<view class="address acea-row row-between-wrapper" v-if="shipping_type === 0" @click="addressTap">
				<view class="addressCon" v-if="addressInfo.realName">
					<view class="name">
						{{ addressInfo.realName }},{{ addressInfo.phone }}
						<!-- <text class="phone">{{ addressInfo.phone }}</text> -->
					</view>
					<view>
						<text class="default font-color-red" v-if="addressInfo.isDefault">[默认]</text>
						{{ addressInfo.province }}{{ addressInfo.city}}{{ addressInfo.district }}{{ addressInfo.detail }}
					</view>
				</view>
				<view class="addressCon" v-else>
					<view class="setaddress">设置收货地址</view>
				</view>
				<view class="iconfont icon-jiantou"></view>
			</view>
			<div class="address acea-row row-between-wrapper" v-if="shipping_type === 1" @click="showStoreList">
				<!-- 直营展示平台信息 -->
				<div v-if="!merId">
					<!-- 判断缓存中是否有门店信息 如果内有就取页面逻辑接口获取的门店信息 -->
					<!-- 平台直营商品自提地址固定为亿久，如果是商家商品自提门店为商家门店信息 -->
					<div class="addressCon" v-if="storeItems">
						<div class="name">
							{{ storeItems.name }},{{storeItems.phone }}
							<!-- <span class="phone">{{storeItems.phone }}</span> -->
						</div>
						<div>{{ storeItems.address}}</div>
					</div>
					<div class="addressCon" v-else>
						<div class="name">
							{{ systemStore.name }}
							<span class="phone">{{systemStore.phone}}</span>
						</div>
						<div>{{ systemStore.address }}</div>
					</div>
					<!-- <div class="iconfont icon-jiantou"></div> -->
				</div>
				<!-- 商家展示商家门店信息 -->
				<div v-if="merId">
					<div class="addressCon">
						<div class="name">
							{{ systemMerStore.name }},{{systemMerStore.phone}}
							<!-- <span class="phone">{{systemMerStore.phone}}</span> -->
						</div>
						<div>{{ systemMerStore.detailedAddress }}</div>
					</div>
				</div>
			</div>
			<view class="address acea-row row-between-wrapper" v-if="shipping_type === 2" @click="addressTap">
				<view class="addressCon" v-if="addressInfo.realName">
					<view class="name">
						{{ addressInfo.realName }}
						<text class="phone">{{ addressInfo.phone }}</text>
					</view>
					<view>
						<text class="default font-color-red" v-if="addressInfo.isDefault">[默认]</text>
						{{ addressInfo.province }}{{ addressInfo.city}}{{ addressInfo.district }}{{ addressInfo.detail }}
					</view>
				</view>
				<view class="addressCon" v-else>
					<view class="setaddress">设置收货地址</view>
				</view>
				<view class="iconfont icon-jiantou"></view>
			</view>
		</view>
		<view class="line">
			<image src="https://qny.yijiumy.com/line.jpg" />
		</view>
		<OrderGoods :evaluate="0" :cartInfo="orderGroupInfo.cartInfo"></OrderGoods>
		<view class="wrapper">
			<view class="item acea-row row-between-wrapper" @click="couponTap" v-if="deduction === false && !source">
				<view>优惠券</view>
				<view class="discount">
					{{ usableCoupon.couponTitle || "请选择" }}
					<text class="iconfont icon-jiantou"></text>
				</view>
			</view>
			<!-- 暂时不是使用积分 -->
			<view style="display: none;" class="item acea-row row-between-wrapper"
				v-if="deduction === false && enableIntegral === true">
				<view>积分抵扣</view>
				<view class="discount">
					<view class="select-btn">
						<view class="checkbox-wrapper">
							<!-- <input type="checkbox" v-model="useIntegral" @click="changeUseIntegral"/> -->
							<checkbox-group @change="changeUseIntegral">
								<label class="well-check">
									<text class="integral">
										当前积分
										<text class="num font-color-red">{{ userInfo.integral || 0 }}</text>
									</text>
									<checkbox value="true" :checked="useIntegral ? true : false"></checkbox>
								</label>
							</checkbox-group>
						</view>
					</view>
				</view>
			</view>
			<view class="item acea-row row-between-wrapper" v-if="shipping_type === 0">
				<view>快递费用</view>
				<view class="discount">
					{{
          orderGroupInfo.priceGroup.storePostage > 0
          ? orderGroupInfo.priceGroup.storePostage
          : "免运费"
          }}
				</view>
			</view>
			<!-- @click="invoiceTap()" -->
			<view v-if="shipping_type === 0 && !merId && !source" class="item acea-row row-between-wrapper">
				<view>是否需要发票</view>
				<view class="discount" @click="invoiceTap()">
					{{ invoiceInfo.invoiceName || "请选择" }}
					<text class="iconfont icon-jiantou"></text>
					
				</view>
			</view>
			<view v-if="shipping_type === 1">
				<view class="item acea-row row-between-wrapper">
					<view>联系人</view>
					<view class="discount">
						<input type="text" placeholder="请填写您的联系姓名" v-model="contacts" />
					</view>
				</view>
				<view class="item acea-row row-between-wrapper">
					<view>联系电话</view>
					<view class="discount">
						<input type="text" placeholder="请填写您的联系电话" v-model="contactsTel" />
					</view>
				</view>
			</view>
			<view class="item" v-if="!source">
				<view>备注信息（150字以内）</view>
				<textarea v-model="mark"></textarea>
			</view>
		</view>
		<view class="wrapper">
			<view class="item">
				<view>支付方式</view>
				<view class="list">
					<view class="payItem acea-row row-middle" :class="active === 'weixin' ? 'on' : ''"
						@click="payItem('weixin')" v-show="isWeixin">
						<view class="name acea-row row-center-wrapper">
							<view class="iconfont icon-weixin2" :class="active === 'weixin' ? 'bounceIn' : ''"></view>
							微信支付
						</view>
						<view class="tip">微信快捷支付</view>
					</view>
					<view class="payItem acea-row row-middle" :class="active === 'weixin' ? 'on' : ''"
						@click="payItem('weixin')" v-show="!isWeixin">
						<view class="name acea-row row-center-wrapper">
							<view class="iconfont icon-weixin2" :class="active === 'weixin' ? 'bounceIn' : ''"></view>
							微信支付
						</view>
						<view class="tip">微信快捷支付</view>
					</view>
					<!-- <view v-if="userInfo.roleLevel == 2" class="payItem acea-row row-middle"
						:class="active === 'yue' ? 'on' : ''" @click="payItem('yue')">
						<view class="name acea-row row-center-wrapper">
							<view class="iconfont icon-icon-test" :class="active === 'yue' ? 'bounceIn' : ''"></view>
							余额支付
						</view>
						<view class="tip">可用余额：{{ userInfo.nowMoney || 0 }}</view>
					</view> -->
				</view>
			</view>
		</view>
		<view class="moneyList">
			<view class="item acea-row row-between-wrapper" v-if="orderPrice.totalPrice !== undefined">
				<view>商品总价：</view>
				<view class="money">￥{{ orderPrice.totalPrice }}</view>
			</view>
			<view class="item acea-row row-between-wrapper" v-if="shipping_type === 0 && orderPrice.payPostage > 0">
				<view>运费：</view>
				<view class="money">￥{{ orderPrice.payPostage }}</view>
			</view>
			<view class="item acea-row row-between-wrapper" v-if="shipping_type === 2 && orderPrice.freight > 0">
				<view>配送费：</view>
				<view class="money">￥{{ orderPrice.freight }}</view>
			</view>
			<view class="item acea-row row-between-wrapper" v-if="shipping_type === 0 && invoiceInfo.invoiceName && merId == '0'">
				<view>发票费用：</view>
				<view class="money">￥{{ orderPrice.serRatio }}</view>
			</view>
			<view class="item acea-row row-between-wrapper" v-if="orderPrice.couponPrice > 0">
				<view>优惠券抵扣：</view>
				<view class="money">-￥{{ orderPrice.couponPrice }}</view>
			</view>
			<view style="display: none;" class="item acea-row row-between-wrapper" v-if="orderPrice.deductionPrice > 0">
				<view>积分抵扣：</view>
				<view class="money">-￥{{ orderPrice.deductionPrice }}</view>
			</view>
			<view class="item acea-row row-between-wrapper" v-if="userInfo.isVip && orderPrice.vipPrice && merId == '0'">
				<view>会员折扣：</view>
				<view class="money">-￥{{ orderPrice.vipPrice }}</view>
			</view>
			
		</view>
		<view style="height:120rpx"></view>
		<view class="footer acea-row row-between-wrapper">
			<view>
				合计:
				<text class="font-color-red">￥{{ orderPrice.payPrice }}</text>
			</view>
			<view class="settlement" @click="createOrder">立即结算</view>
		</view>
		<CouponListWindow v-on:couponchange="changecoupon($event)" v-model="showCoupon" :price="orderPrice.totalPrice"
			:checked="usableCoupon.id" @checked="changeCoupon" :cartid="cartid"></CouponListWindow>
		<AddressWindow @checked="changeAddress" @redirect="addressRedirect" v-model="showAddress"
			:checked="addressInfo.id" ref="mychild"></AddressWindow>

		<!-- 扩展发票弹窗 -->
		<InvoiceWindow v-model="isInvoice" @redirect="invoiceRedirect" :value="true" @checked="changeInvoice" :checked="invoiceInfo.invoiceId" ref="myInvoice"></InvoiceWindow>
		<u-loading-page :loading="isLoading" loading-text="生成订单中..." bg-color="rgba(0, 0, 0, .5)"></u-loading-page>
	</view>
</template>

<script>
	import OrderGoods from "@/components/OrderGoods";
	import CouponListWindow from "@/components/CouponListWindow";
	import InvoiceWindow from "@/components/InvoiceWindow";
	import AddressWindow from "@/components/AddressWindow";
	import {
		postOrderConfirm,
		postOrderComputed,
		createOrder
	} from "@/api/order";
	import {
		mapGetters
	} from "vuex";
	import {
		handleOrderPayResults,
		// subscribeMessage
	} from "@/libs/order";
	import {
		weappPay
	} from "@/libs/wechat";
	import {
		isWeixin,
		handleErrorMessage
	} from "@/utils";
	import {
		copyObj
	} from "@/utils/copyObj";

	const NAME = "OrderSubmission",
		_isWeixin = isWeixin();
	export default {
		name: NAME,
		components: {
			OrderGoods,
			CouponListWindow,
			AddressWindow,
			InvoiceWindow
		},
		props: {},
		data: function() {
			return {
				isLoading: false,
				offlinePayStatus: 2,
				from: this.$deviceType,
				deduction: true,
				enableIntegral: true,
				enableIntegralNum: 0,
				isWeixin: _isWeixin,
				pinkId: 0,
				// active: _isWeixin ? "weixin" : "yue",
				active: "weixin",
				showCoupon: false,
				showAddress: false,
				addressInfo: {},
				couponId: 0,
				orderGroupInfo: {
					priceGroup: {},
				},
				usableCoupon: {},
				addressLoaded: false,
				useIntegral: false,
				orderPrice: {
					payPrice: "计算中",
				},
				mark: "",
				systemStore: {},
				systemMerStore: {},
				shipping_type: 0,
				contacts: "",
				contactsTel: "",
				storeSelfMention: 0,
				cartid: "",
				// 扩展 发票资料
				isInvoice: false,
				invoiceLoaded: false,
				invoiceInfo: {} ,// 选中的发票信息
				merId: 0, // 是否直营商品 0 为直营商品
				source: '' // 来源：payment为买单奖品进来的
			};
		},
		computed: mapGetters(["userInfo", "storeItems"]),
		watch: {
			useIntegral() {
				this.computedPrice();
			},
			$yroute(n) {
				if (n.name === NAME) this.getCartInfo();
			},
			shipping_type() {
				if(this.orderGroupInfo.orderKey) this.computedPrice();
			},
		},
		onLoad: function() {
			let that = this;
			that.$store.dispatch("getUser", true);
			console.log(that.$yroute);
			if (that.$yroute.query.pinkid !== undefined) {
				that.pinkId = that.$yroute.query.pinkid;
			}
			if (that.$yroute.query.id !== undefined) {
				that.cartid = that.$yroute.query.id;
				that.merId = that.$yroute.query.merId * 1;
				that.source = that.$yroute.query.source || ''
				// 判断当前是直营还是非直营，直营默认快递配送方式，非直营默认自提方式
				that.shipping_type = !that.merId ? 0 : 1
			}
			that.getCartInfo();
		},
		methods: {
			showStoreList() {
				// 平台直营目前没有多门店逻辑
				return false
				this.$store.commit("get_to", "orders");
				this.$yrouter.push({
					path: "/pages/shop/StoreList/index",
				});
			},
			addressType: function(index) {
				// && !this.merId
				// if (index && !this.systemStore.id) {
				// 	uni.showToast({
				// 		title: "暂无门店信息，您无法选择到店自提！",
				// 		icon: "none",
				// 		duration: 2000,
				// 	});
				// 	return;
				// }
				// console.log(this);
				this.shipping_type = index;
			},
			changeUseIntegral: function(e) {
				// this.computedPrice();
				this.useIntegral = e.mp.detail.value[0];
			},
			computedPrice() {
				let shipping_type = this.shipping_type;
				postOrderComputed(this.orderGroupInfo.orderKey, {
					addressId: this.addressInfo.id,
					useIntegral: this.useIntegral ? 1 : 0,
					couponId: this.usableCoupon.id || 0,
					shipping_type: parseInt(shipping_type) + 1,
					invoiceId: this.invoiceInfo.invoiceId, // 扩展的发票id
					shopId: this.merId,
					type: !this.source ? "" : "1"
				}).then((res) => {
					// 获取达达订单号，支付的时候传递
					const data = res.data;
					if (data.status === "EXTEND_ORDER") {
						this.$yrouter.replace({
							path: "/userOrderPack/pages/order/OrderDetails/index",
							query: {
								id: data.result.orderId,
							},
						});
					} else {
						this.orderPrice = data.result;
					}
				});
			},
			getCartInfo() {
				const cartIds = this.$yroute.query.id;
				if (!cartIds) {
					uni.showToast({
						title: "参数有误",
						icon: "none",
						duration: 2000,
					});
					return this.$yrouter.back();
				}
				postOrderConfirm({
					cartId: cartIds,
					type: !this.source ? "" : "1"
				}).then((res) => {
						console.log(res, 999999);
						console.log(res.data.systemStore || {}, 999999);
						this.offlinePayStatus = res.data.offline_pay_status;
						this.orderGroupInfo = res.data;
						this.deduction = res.data.deduction;
						this.usableCoupon = res.data.usableCoupon || {};
						this.addressInfo = res.data.addressInfo || {};
						this.invoiceInfo = res.data.invoiceInfo || {}
						// 用来显示到店自提的店铺地址
						this.systemStore = res.data.systemStore || {};
						this.systemMerStore = res.data.systemMerStore || {};
						this.storeSelfMention = res.data.storeSelfMention;
						this.computedPrice();
					})
					.catch(() => {
						uni.showToast({
							title: "加载订单数据失败",
							icon: "none",
							duration: 2000,
						});
					});
			},
			addressTap: function() {
				this.showAddress = true;
				if (!this.addressLoaded) {
					this.addressLoaded = true;
					this.$refs.mychild.getAddressList();
				}
			},
			invoiceTap: function() {
				this.isInvoice = true;
				if(!this.invoiceLoaded) {
					this.invoiceLoaded = true
					this.$refs.myInvoice.getInvoice();
				}
			},
			addressRedirect() {
				this.addressLoaded = false;
				this.showAddress = false;
			},
			invoiceRedirect() {
				this.invoiceLoaded = false;
				this.isInvoice = false;
			},
			couponTap: function() {
				this.showCoupon = true;
			},
			changeCoupon: function(coupon) {
				if (!coupon) {
					this.usableCoupon = {
						couponTitle: "不使用优惠券",
						id: 0,
					};
				} else {
					this.usableCoupon = coupon;
				}
				this.computedPrice();
			},
			changeInvoice: function(invoice) {
				if (invoice.invoiceId == this.invoiceInfo.invoiceId) {
					this.invoiceInfo = {}
				} else {
					this.invoiceInfo = invoice
				}
				// console.log(invoice)
				
				// console.log(this.invoiceInfo)
				// 重新计算金额 需要把发票id给到后端
				this.computedPrice()
			},
			payItem: function(index) {
				this.active = index;
			},
			changeAddress(addressInfo) {
				this.addressInfo = addressInfo;
				this.computedPrice();
			},
			createOrder() {
				let shipping_type = this.shipping_type;
				if (!this.active) {
					uni.showToast({
						title: "请选择支付方式",
						icon: "none",
						duration: 2000,
					});
					return;
				}
				if (!this.addressInfo.id && (this.shipping_type == 0 || this.shipping_type == 2)) {
					uni.showToast({
						title: "请选择收货地址",
						icon: "none",
						duration: 2000,
					});
					return;
				}

				if (this.shipping_type == 1) {
					if (
						(this.contacts === "" || this.contactsTel === "")
					) {
						uni.showToast({
							title: "请填写联系人或联系人电话",
							icon: "none",
							duration: 2000,
						});
						return;
					}

					if (!/^1(3|4|5|7|8|9|6)\d{9}$/.test(this.contactsTel)) {
						uni.showToast({
							title: "请填写正确的手机号",
							icon: "none",
							duration: 2000,
						});
						return;
					}
					if (!/^[\u4e00-\u9fa5\w]{2,16}$/.test(this.contacts)) {
						uni.showToast({
							title: "请填写您的真实姓名",
							icon: "none",
							duration: 2000,
						});
						return;
					}
				}

				// uni.showLoading({
				// 	title: "生成订单中",
				// });
				this.isLoading = true
				let from = {};
				if (this.$deviceType == "app") {
					from.from = "app";
				}
				// #ifdef MP-WEIXIN
				// subscribeMessage()
				// #endif
				console.log(this.storeItems)
				console.log(this.systemStore.id)
				createOrder(this.orderGroupInfo.orderKey, {
						realName: this.contacts,
						phone: this.contactsTel,
						addressId: this.addressInfo.id,
						useIntegral: this.useIntegral ? 1 : 0,
						couponId: this.usableCoupon.id || 0,
						payType: this.active,
						pinkId: this.pinkId,
						seckillId: this.orderGroupInfo.seckill_id,
						combinationId: this.orderGroupInfo.combination_id,
						bargainId: this.orderGroupInfo.bargain_id,
						from: this.from,
						mark: this.mark || "",
						shippingType: parseInt(shipping_type) + 1,
						storeId: !this.merId ?  this.systemStore.id : this.systemMerStore.id, // storeId 如果是直营 传入systemStore.id
						...from,
						// invoiceId为发票id 只有线上配送订单才有
						invoiceId: this.invoiceInfo.invoiceId,
						merId: this.systemMerStore.uid,
						// 传递金额计算返回的达达订单号
						dadaOrderId: this.orderPrice.dadaOrderId ? this.orderPrice.dadaOrderId : '',
						type: !this.source ? "" : "1"
					})
					.then((res) => {
						// uni.hideLoading();
						this.isLoading = false
						handleOrderPayResults.call(this, res.data, "create", this.active);
					})
					.catch((err) => {
						this.isLoading = false
						handleErrorMessage(err, "创建订单失败");
					});
			},
		},
	};
</script>

<style scoped lang="less">
	.order-submission .wrapper .shipping select {
		color: #999;
		padding-right: 0.15 * 100rpx;
	}

	.order-submission .wrapper .shipping .iconfont {
		font-size: 0.3 * 100rpx;
		color: #515151;
	}

	.order-submission .allAddress {
		width: 100%;
		background-image: linear-gradient(to bottom, #9f2b45 0%, #9f2b45 100%);
		background-image: -webkit-linear-gradient(to bottom,
				#9f2b45 0%,
				#9f2b45 100%);
		background-image: -moz-linear-gradient(to bottom, #9f2b45 0%, #9f2b45 100%);
		// padding-top: 1 * 100rpx;
		padding-top: 20rpx;
	}

	.order-submission .allAddress .nav {
		margin: 0 auto;
		padding: 0 30rpx;
		width: 100%;
		box-sizing: border-box;
	}

	.order-submission .allAddress .nav .item {
		flex: 1;
		position: relative;
		color: #fff;
	}

	.order-submission .allAddress .nav .item.on {
		position: relative;
	}
	.order-submission .allAddress .nav .item.on2 {
		position: relative;
	}

	.order-submission .allAddress .nav .item.on:before {
		position: absolute;
		bottom: 0;
		content: "快递配送";
		font-size: 0.28 * 100rpx;
		display: block;
		height: 0;
		left: 0;
		right: 0;
		border-width: 0.4 * 100rpx;
		border-style: solid;
		border-color: #fff;
		z-index: 9;
		text-align: center;
		line-height: 0.14 * 100rpx;
	}
	.order-submission .allAddress .nav .item:nth-of-type(1).on2:before {
		content: "快递配送";
		border-width: 0.4 * 100rpx;
	}

	.order-submission .allAddress .nav .item.on2:before {
		position: absolute;
		bottom: 0;
		content: "到店自提";
		font-size: 0.28 * 100rpx;
		display: block;
		height: 0;
		left: 0;
		right: 0;
		border-width: 0.4 * 100rpx;
		border-style: solid;
		border-color: #d5e6e6;
		text-align: center;
		line-height: 0.14 * 100rpx;
	}
	.order-submission .allAddress .nav .item:nth-of-type(2).on:before {
		content: "到店自提";
		border-width: 0.4 * 100rpx;
	}
	.order-submission .allAddress .nav .item.active {
		color: #9f2b45;
		background: #fff;
	}

	

	

	

	.order-submission .allAddress .address {
		width: 6.91 * 100rpx;
		height: 1.5 * 100rpx;
		margin: 0 auto;
		box-sizing: border-box;
	}

	.order-submission .allAddress .line {
		width: 7.1 * 100rpx;
		margin: 0 auto;
	}

	.order-submission .wrapper .item .discount input::placeholder {
		color: #ccc;
	}
</style>